
import * as config from './config'
import utils from './utils';
import storage from "./storage";
import {CHANNEL_ID} from "./config";

let ossConfig = null,
    loadingLen = 0


/**
 * 请求封装
 */
export default {
    request(param, loginRequest) {
        return new Promise((resolve, reject) => {
            const urlData = []
            let header = {},
                data = {},
                _temp = utils.cloneObject(param)

            if (param.header) header = Object.assign({}, header, param.header);

            data.channelId = config.CHANNEL_ID

            if (param.data) data = Object.assign({}, data, param.data);

            const token = storage.getToken()
            if(token&&!data.token) {
                header.token = token
            }

            param.method = param.method || 'get'
            if ((param.method.toLocaleLowerCase() === 'get' || param.method.toLocaleLowerCase() === 'delete') && data &&
                typeof data === 'object') {
                for (let i in data) {
                    urlData.push(`${i}=${data[i]}`)
                }
                param.url += urlData.length > 0 ? (param.url.indexOf('?') > -1 ? '&' : '?') + urlData.join('&') : ''
                data = {}
            }

            header['Content-Type'] = 'application/json;charset=UTF-8'
            const url = `${(param.httpHost || config.HTTP_URL)}${param.url}`

            if(!param.noLoading) {
                loadingLen++
                utils.showLoading()
            }

            uni.request({
                url: url + "?c=" + config.CHANNEL_ID,
                data,
                header,
                method: param.method,
                enableChunked: param.enableChunked || false,
                success: res => {
                    if(!param.noLoading) {
                        utils.hideLoading()
                        // loadingLen--
                        // setTimeout(v => {
                        //     loadingLen <= 0 && utils.hideLoading()
                        // }, 500)
                    }
                    console.log('接口成功', url, data, res)
                    if (param.noCheck) {
                        resolve(res.data)
                    } else {
                        this.checkCode(res, resolve, reject, _temp, loginRequest)
                    }
                },
                fail(err) {
                    if(!param.noLoading) {
                        utils.hideLoading()
                        // loadingLen--
                        // setTimeout(v => {
                        //     loadingLen <= 0 && utils.hideLoading()
                        // }, 500)
                    }
                    console.log('接口失败', url, data, err)
                    utils.toast('网络异常')
                    console.log(JSON.stringify(param))
                    typeof param.fail === 'function' && param.fail(err)
                }
            })

        })
    },
    checkCode(res, resolve, reject, tempData, loginRequest) {
        if(res.data.code === 200) {
            resolve(res.data)
        }else{
            switch (res.data.code){
                case '901':
                    reject(res.data)
                    utils.toast(res.data.info || '服务器异常')
                    break;
                case 401:
                    utils.gotoLogin()
                    break
                default:
                    utils.toast(res.data.msg || '服务器异常，未知状态')
                    reject(res.data)
            }
        }
    },


    uploadFile(url, file, fdata = {}) {
        return new Promise((resolve, reject) => {
            const header = {}
            const token = storage.getToken()
            if(token) {
                header.token = token
            }
            let data = {
                channelId: config.CHANNEL_ID
            }
            if (fdata) data = Object.assign({}, data, fdata);

            const surl = `${config.HTTP_URL}${url}`
            utils.showLoading()
            uni.uploadFile({
                url: surl + "?c=" + config.CHANNEL_ID,
                filePath: file,
                name: 'file',
                header,
                formData: data,
                success: (uploadFileRes) => {
                    utils.hideLoading()
                    uploadFileRes.data = JSON.parse(uploadFileRes.data)
                    this.checkCode(uploadFileRes, resolve, reject)
                },
                fail: (uploadFileRes) => {
                    utils.hideLoading()
                    reject()
                }
            });
        })

    },


    sse: function (param) {
        const data = Object.assign({}, param.data),
            header = Object.assign({}, param.header);


        return uni.request({
            url: `${(param.httpHost || config.HTTP_URL)}${param.url}`,
            data,
            header,
            timeout: 30000,
            responseType: 'text',
            method: "get",
            enableChunked: true,
        })
    },

    //get方法
    get: function (param) {
        return this.request({
            ...param,
            method: 'get'
        })
    },
    //post方法
    post: function (param) {
        return this.request({
            ...param,
            method: 'post'
        })
    },
    //put方法
    put: function (param) {
        return this.request({
            ...param,
            method: 'PUT'
        });
    },
    //delete方法
    delete: function (param) {
        return this.request({
            ...param,
            method: 'DELETE'
        });
    },

}
